<template>
    <div>
        <el-row>
            <el-card>
                <div style="margin-top: 15px;" id="app">
                    <el-form :inline="true" :model="selectForm" class="demo-form-inline" ref="selectFormRef">
                        <el-input
                                v-model="selectForm.id"
                                placeholder="请输入区域id"
                                style="width: 15%"
                        ></el-input>
                        <el-select v-model="selectForm.role" placeholder="区域类型" style="width: 15%">
                            <el-option label="校门" value="A"></el-option>
                            <el-option label="宿舍楼" value="B"></el-option>
                            <el-option label="教学楼" value="C"></el-option>
                            <el-option label="行政楼" value="D"></el-option>
                            <el-option label="图书馆" value="E"></el-option>
                        </el-select>
                        <el-input
                                v-model="selectForm.name"
                                placeholder="请输入区域名称"
                                style="width: 15%"
                        ></el-input>
                        <el-button type="primary" @click="select()">查询</el-button>
                        <el-button type="primary" @click="resetSelect()">重置</el-button>
                    </el-form>
                    <el-table
                            v-loading="loading"
                            :data="tableData"
                            @selection-change="handleSelectionChange"
                            style="width: 100%">
                        <el-table-column
                                type="selection"
                                width="55">
                        </el-table-column>
                        <el-table-column prop="id" label="区域id" sortable width="150"></el-table-column>
                        <el-table-column prop="name" label="区域名称" sortable width="150"></el-table-column>
                        <el-table-column prop="role" label="权限" sortable width="100"></el-table-column>
                        <el-table-column prop="number" label="估计人数" sortable width="100"></el-table-column>
                        <el-table-column prop="beginTime" label="起始时间点" sortable width="150"></el-table-column>
                        <el-table-column prop="endTime" label="结束时间点" sortable width="150"></el-table-column>
                        <el-table-column align="right" width="90">
                            <template slot="header">
                                <el-button type="primary" @click="save=true" size="mini" plain>添加</el-button>
                            </template>
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" plain @click="getRecord(scope.row.id)"
                                           v-if="scope.row">通行记录
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column align="right" width="130">
                            <template slot="header">
                                <el-button type="primary" @click="exportExcel()" size="mini" plain>导出所选中信息</el-button>
                            </template>
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" plain @click="getImg(scope.row.id),openImg=true"
                                           v-if="scope.row">区域二维码
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column align="right" width="150">
                            <template slot="header">
                                <el-button type="danger" @click="deleteMessages()" size="mini" plain>删除所选中信息</el-button>
                            </template>
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" plain @click="edit=true,getForm(scope.row.id)"
                                           v-if="scope.row&&update_button==1">修改
                                </el-button>
                                <el-button size="mini" type="danger" plain @click="deleteArea(scope.row)"
                                           v-if="scope.row&&delete_button==1">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                            style="margin: 15px 0px;"
                            prev-text="上一页" next-text="下一页" background
                            layout="prev, pager, next, sizes, jumper, total"
                            :page-sizes="[5,10,20,40,100,500,50000]"
                            :page-size="pageSize"
                            :total="total"
                            :current-page="pageNow"
                            @current-change="findPage"
                            @size-change="findSize">
                    </el-pagination>
                    <el-dialog
                            :visible.sync="openImg"
                            width="400px"
                    >
                        <template slot-scope="scope">
                            <div>进入区域二维码：</div>
                            <vue-qr  ref="qr" :text="imgA" :size="200"></vue-qr>
                            <el-button @click="downloadImgA()">下载二维码</el-button>
                            <div>离开区域二维码：</div>
                            <vue-qr  :text="imgB" :size="200"></vue-qr>
                            <el-button @click="downloadImgB()">下载二维码</el-button>
                        </template>
                    </el-dialog>

                    <el-dialog title="添加区域信息" :visible.sync="save" width="25%">
                        <el-form ref="sForm" label-width="80px" :model="saveForm">
<!--                            <el-form-item label="区域id" prop="id">-->
<!--                                <el-input v-model="saveForm.id"></el-input>-->
<!--                            </el-form-item>-->
                            <el-form-item label="区域名称" prop="name">
                                <el-input v-model="saveForm.name" style="width: 220px"></el-input>
                            </el-form-item>
                            <el-form-item prop="role" label="区域类型/权限">
                                <el-select v-model="saveForm.role" placeholder="区域类型">
                                    <el-option label="校门" value="A"></el-option>
                                    <el-option label="宿舍楼" value="B"></el-option>
                                    <el-option label="教学楼" value="C"></el-option>
                                    <el-option label="行政楼" value="D"></el-option>
                                    <el-option label="图书馆" value="E"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="开放时间:">
                                <el-time-select placeholder="起始时间" v-model="saveForm.beginTime"
                                                :picker-options="{
                                      start: '00:00',
                                      step: '00:30',
                                      end: '24:00'
                                      }">
                                </el-time-select>
                                <el-time-select placeholder="结束时间" v-model="saveForm.endTime"
                                                :picker-options="{
                                      start: '00:00',
                                      step: '00:30',
                                      end: '24:00',
                                      minTime: saveForm.beginTime
                                      }">
                                </el-time-select>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
            <el-button @click="save = false">取 消</el-button>
            <el-button type="primary" @click="save = false,saveArea('sForm')">确 定</el-button>
          </span>
                    </el-dialog>
                    <el-dialog title="修改区域信息" :visible.sync="edit" width="25%">
                        <el-form ref="editForm" label-width="80px" :model="eform">
                            <el-form-item label="区域id" prop="id">
                                <el-input v-model="eform.id" disabled style="width: 220px"></el-input>
                            </el-form-item>
                            <el-form-item label="区域名称" prop="name">
                                <el-input v-model="eform.name" style="width: 220px"></el-input>
                            </el-form-item>
                            <el-form-item prop="role" label="区域类型/权限">
                                <el-select v-model="eform.role" placeholder="区域类型">
                                    <el-option label="校门" value="A"></el-option>
                                    <el-option label="宿舍楼" value="B"></el-option>
                                    <el-option label="教学楼" value="C"></el-option>
                                    <el-option label="行政楼" value="D"></el-option>
                                    <el-option label="图书馆" value="E"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="开放时间:">
                                <el-time-select placeholder="起始时间" v-model="eform.beginTime"
                                                :picker-options="{
                                      start: '00:00',
                                      step: '00:30',
                                      end: '24:00'
                                      }">
                                </el-time-select>
                                <el-time-select placeholder="结束时间" v-model="eform.endTime"
                                                :picker-options="{
                                      start: '00:00',
                                      step: '00:30',
                                      end: '24:00',
                                      minTime: eform.beginTime
                                      }">
                                </el-time-select>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
            <el-button @click="edit = false">取 消</el-button>
            <el-button type="primary" @click="edit = false,updateArea('editForm')">确 定</el-button>
          </span>
                    </el-dialog>
                </div>
            </el-card>
        </el-row>
        <el-row>
            <el-divider content-position="left">Excel 导入</el-divider>
            <el-card>
                <el-row class="mb20">
                    <el-upload
                            action="/xxx/xxx"
                            accept=".xls, .xlsx"
                            :on-change="impotExcel"
                            :auto-upload="false"
                            multiple
                            :limit="1"
                            :file-list="fileList"
                    >
                        <el-button size="small" :plain="true" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传 .xls .xlsx 文件，且不超过500kb</div>
                    </el-upload>
                    <el-button size="small" type="primary" @click="getMessage()">确认保存</el-button>
                </el-row>
            </el-card>
        </el-row>



    </div>
</template>

<script>
    import echarts from 'echarts'
    import XLSX from 'xlsx'
    import baseUrl from '@/utils/global.js'
    import getPerson from "../plugins/getPerson";
    var list = []


    export function validateAccountNumber(str) {
        const reg = /^([1-9]{1})$/
        return reg.test(str)
    }

    export default {

        data() {
            let num = /^(0|\+?[1-9][0-9]*)$/
            let isNum = (rule, value, callback) => {
                if (!num.test(value)) {
                    return callback(new Error('格式错误'))
                } else {
                    callback()
                }
            }
            let percent = /^(?:[1-9]?\d|100)$/
            let isPercent = (rule, value, callback) => {
                if (!percent.test(value)) {
                    return callback(new Error('请输入0-100的整数'))
                } else {
                    callback()
                }
            }
            const _this = this
            return {
                imgA:'',
                imgB:'',
                fileList: [],
                save: false,
                edit: false,
                openImg:false,
                delete_button: 1,
                update_button: 1,
                total: 0,//总页数，从后台查询
                pageNow: 1,//当前页数，默认为1
                pageSize: 5,//当前页显示的数据条数，默认为5
                loading: false,
                tableData: null,
                selectData: [],
                selectData2: [],
                saveForm: {
                    id: '',
                    name: '',
                    role: '',
                    number: 0,
                    beginTime: '',
                    endTime: '',
                },
                eform: {
                    id: '',
                    name: '',
                    role: '',
                    number: 0,
                    beginTime: '',
                    endTime: '',
                },
                selectForm: {
                    id:null,
                    role: null,
                    name: null,
                }

            }
        },
        mounted() {
        },
        methods: {
            downloadImgA(){
                let a = document.createElement('a');
                // 下载图名字
                a.download = Date.parse(new Date());
                //url
                a.href = this.$refs.qr.$el.src;
                //合成函数，执行下载
                a.dispatchEvent(new MouseEvent('click'))
            },
            downloadImgB(){
                let a = document.createElement('a');
                // 下载图名字
                a.download = Date.parse(new Date());
                //url
                a.href = this.$refs.qr.$el.src;
                //合成函数，执行下载
                a.dispatchEvent(new MouseEvent('click'))
            },
            getImg(id){
                this.imgA="http://8.131.99.110/#/?id="+id+"&direction=A"//进入二维码
                this.imgB="http://8.131.99.110/#/?id="+id+"&direction=B"//离开二维码
            },
            getRecord(id){
                this.$router.push({path:'/home/recordOfArea',query: {id:id}})
            },
            select(){
                let list=[];
                const _this = this;
                let pageRequest = {
                    pageNow: 1,
                    pageSize: 100000,
                };
                this.$http.area.findPage(pageRequest).then((res) => {
                    // console.log(res.data);
                    this.tableData = res.data;
                    this.total = res.total;
                    for (let i=0;i<this.tableData.length;i++){
                        if(
                            (
                                this.selectForm.role==null
                                ||this.tableData[i].role.indexOf(this.selectForm.role)==0
                            )
                            &&(
                                this.selectForm.name==null
                                ||this.tableData[i].name.indexOf(this.selectForm.name)==0
                            )
                            &&(
                                this.selectForm.id==null
                                ||this.tableData[i].id==parseInt(this.selectForm.id)
                            )
                        ){
                            list.push(this.tableData[i])
                        }
                    }
                    this.tableData=list
                });
            },
            resetSelect(){
                this.selectForm= {
                    id: null,
                    name: null,
                    role: null,
                },
                    this.findAllTableDataByPage();
            },
            findAllTableDataByPage() {
                let pageRequest = {
                pageNow: this.pageNow,
                pageSize: this.pageSize
                 };
                this.$http.area.findPage(pageRequest).then((res) => {
                     console.log(res.data);
                    this.tableData = res.data
                    this.total = res.total
                })
            },
            impotExcel(file, fileList) {
                let that = this
                let f = file.raw
                let x
                let reader = new FileReader()
                reader.onload = function (e) {
                    let data = new Uint8Array(e.target.result)
                    var workbook = XLSX.read(data, {type: 'array'})
                    let json = XLSX.utils.sheet_to_json(workbook.Sheets.Sheet1) // 取第一个sheet
                    that.jsonData = json
                    x = json
                    that.jsonStr = JSON.stringify(json)
                    that.tableData = json
                }
                //this.$http.post("/studentMessage/save",message);
                reader.readAsArrayBuffer(f)
                this.$message({
                    message: 'Excel内信息已展示至表格内',
                    type: 'success'
                })
                this.delete_button = 0
                this.update_button = 0
            },
            getMessage() {
                this.$confirm('此操作将保存进数据库, 是否继续?', '提示', {
                    confirmButtonText: '继续',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '保存成功!'
                    })
                    this.$http.area.saveFromExcel( this.jsonData).then(function (resp) {
                        if (resp.code == 2000) location.reload();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消保存'
                    })
                })
            },
            findPage(page) {
                // console.log('当前页数：' + page)
                this.pageNow = page
                this.findAllTableDataByPage()
            },
            findSize(size) {
                // console.log('当前页面记录条数：' + size)
                this.pageSize = size
                this.findAllTableDataByPage()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
                //console.log(val)
            },
            saveArea(formName) {
                const _this = this
                console.log(_this.saveForm)
                this.$http.area.save( _this.saveForm).then(function (resp) {
                    if (resp.code == 2000) {
                        _this.$message.success('添加成功')
                        location.reload()
                    }
                })

            },
            updateArea(formName) {
                const _this = this
                this.$http.area.update(this.eform).then((resp) => {
                    if (resp.code == 2000) _this.$message.success('修改成功')
                    location.reload()
                })
            },
            getForm(id) {
                const _this = this
                console.log(id)
                this.$http.area.findOne(id).then((resp) => {
                        switch (resp.data.sex) {
                            case 0:
                                resp.data.sex = '男'
                                break
                            case 1:
                                resp.data.sex = '女'
                                break
                        }
                        _this.eform = resp.data

                    })
            },
            deleteArea(row) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.area.del(row.id).then((resp) => {
                        if (resp.code == 2000)
                            location.reload();
                    })

                    this.$message({
                            type: 'success',
                            message: '删除成功!'
                        }
                    )
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
                const _this = this
            },
            deleteMessages() {
                this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$message({
                            type: 'success',
                            message: '删除成功!'
                        }
                    )
                    this.$http.area.delMgs(this.multipleSelection).then(function (resp) {
                        if (resp.code == 2000) location.reload();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
            exportExcel() {
                //创建book
                var wb = XLSX.utils.book_new()
                //json转sheet
                var ws = XLSX.utils.json_to_sheet(this.multipleSelection, {})
                //设置列宽
                ws['!cols'] = [
                    {width: 15},
                    {width: 15},
                    {width: 30}
                ]
                var timestamp = new Date().getTime()
                //sheet写入book
                XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
                //输出
                XLSX.writeFile(wb, 'file_' + timestamp + '.xlsx')
            },
        },
        created() {
            const _this = this
            _this.findAllTableDataByPage()
        }
    }
</script>

<style scoped>

</style>
